package com.cershy.chatroomserver.controller;

import com.cershy.chatroomserver.annotation.Userid;
import com.cershy.chatroomserver.dto.InviteGroupRequest;
import com.cershy.chatroomserver.dto.JoinGroupRequest;
import com.cershy.chatroomserver.dto.CreateGroupRequest;
import com.cershy.chatroomserver.entity.Group;
import com.cershy.chatroomserver.entity.UserList;
import com.cershy.chatroomserver.mapper.GroupMapper;
import com.cershy.chatroomserver.service.UserListService;
import com.cershy.chatroomserver.utils.GroupIdGenerator;
import com.cershy.chatroomserver.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
@RequestMapping("/api/v1/user-list")
public class UserListController {
    private static final Logger log = LoggerFactory.getLogger(UserListController.class);
    @Resource
    UserListService userListService;

    // 获取用户加入的所有群聊
    @GetMapping("/groups")
    public Object getGroups(@Userid String userId) {
        List<UserList> groups = userListService.getGroupsByUserId(userId);
        return ResultUtil.Succeed(groups);
    }

    // 加入群聊
    @PostMapping("/join")
    public Object joinGroup(@Userid String userId, @RequestBody JoinGroupRequest request) {
        String groupId = request.getGroupId();
        String role = request.getRole();

        if (groupId == null || groupId.isEmpty()) {
            return ResultUtil.Fail("groupId 参数缺失");
        }

        // 默认角色为 user
        if (role == null || role.isEmpty()) {
            role = "user";
        }

        boolean success = userListService.addUserToGroup(userId, groupId, role);
        return ResultUtil.Succeed(success);
    }


    // 离开群聊
    @PostMapping("/leave")
    public Object leaveGroup(@Userid String userId, @RequestParam String groupId) {
        boolean success = userListService.removeUserFromGroup(userId, groupId);
        return ResultUtil.Succeed(success);
    }

    // 检查是否在群聊中
    @GetMapping("/check")
    public Object checkInGroup(@Userid String userId, @RequestParam String groupId) {
        boolean inGroup = userListService.isUserInGroup(userId, groupId);
        return ResultUtil.Succeed(inGroup);
    }

    // 获取群主ID
// 修改前：
// public Result getGroupOwner(@RequestParam(required = false) String groupId)

    // 修改后：
    @GetMapping("/group-owner")
    public Object getGroupOwner(@RequestParam(required = false) String groupId) {

        String ownerId = userListService.getGroupOwnerId(groupId);
        return ownerId != null ? ResultUtil.Succeed(ownerId) : ResultUtil.Fail("群主不存在");
    }

    /**
     * 获取指定群组的所有成员信息
     */
    @GetMapping("/group-users")
    public Object getGroupUsers(@RequestParam String groupId) {
        if (groupId == null || groupId.isEmpty()) {
            log.warn("groupId 参数缺失");
            return ResultUtil.Fail("缺少必要参数: groupId");
        }

        try {
            List<Map<String, Object>> users = userListService.getGroupUsers(groupId);
            return users != null && !users.isEmpty()
                    ? ResultUtil.Succeed(users)
                    : ResultUtil.Fail("该群组暂无成员");
        } catch (Exception e) {
            log.error("获取群组成员失败", e);
            return ResultUtil.Fail("内部服务器错误");
        }
    }

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private GroupIdGenerator GroupIdGenerator;

    @PostMapping("/create")
    public Object createGroup(@Userid String userId, @RequestBody CreateGroupRequest request) {
        if (request.getName() == null || request.getName().isEmpty()) {
            return ResultUtil.Fail("群组名称不能为空");
        }

        // 👇 新增：检查群名是否已存在
        Group existingGroup = groupMapper.selectByName(request.getName());
        if (existingGroup != null) {
            return ResultUtil.Fail("该群名已被占用，请更换群名");
        }

        try {
            String groupId = GroupIdGenerator.generateGroupId();

            Group group = new Group();
            group.setId(groupId);
            group.setName(request.getName());
            group.setGroupNumber("GRP-" + System.currentTimeMillis());
            group.setAvatar(request.getAvatar());
            group.setLeader(request.getLeader());
            group.setLeaderId(userId);
            group.setCreateTime(new Date());
            group.setUpdateTime(new Date());

            groupMapper.insert(group);

            boolean joined = userListService.addUserToGroup(userId, groupId, "leader");
            if (!joined) {
                groupMapper.deleteById(groupId);
                return ResultUtil.Fail("创建群组失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("groupId", groupId);
            result.put("name", request.getName());
            result.put("groupNumber", group.getGroupNumber());
            result.put("ownerId", userId);

            return ResultUtil.Succeed(result);
        } catch (Exception e) {
            log.error("创建群组时发生异常", e);
            return ResultUtil.Fail("创建群组失败: " + e.getMessage());
        }
    }

    /**
     * 管理员邀请用户加入群组
     */
    @PostMapping("/invite")
    public Object inviteUserToGroup(
            @Userid String adminId,
            @RequestBody InviteGroupRequest request) {

        String groupId = request.getGroupId();
        String targetUserId = request.getTargetUserId();
        String role = request.getRole();

        if (groupId == null || targetUserId == null) {
            return ResultUtil.Fail("缺少必要参数");
        }

        // 1. 检查当前用户是否为群主
        String groupOwnerId = userListService.getGroupOwnerId(groupId);
        if (groupOwnerId == null || !groupOwnerId.equals(adminId)) {
            return ResultUtil.Fail("您没有权限邀请他人加入");
        }

        // 2. 检查目标用户是否已加入
        if (userListService.isUserInGroup(targetUserId, groupId)) {
            return ResultUtil.Fail("该用户已加入群组");
        }

        // 3. 添加用户到群组
        boolean success = userListService.addUserToGroup(targetUserId, groupId, role != null ? role : "user");

        if (success) {
            log.info("管理员 {} 成功邀请用户 {} 加入群组 {}", adminId, targetUserId, groupId);
            return ResultUtil.Succeed(true);
        } else {
            log.error("邀请用户 {} 加入群组 {} 失败", targetUserId, groupId);
            return ResultUtil.Fail("邀请失败");
        }
    }

    @PostMapping("/exit")
    public Object exitGroup(@Userid String currentUserId, @RequestBody Map<String, String> payload) {
        String userId = payload.get("userId");
        String groupId = payload.get("groupId");

        if (userId == null || groupId == null) {
            return ResultUtil.Fail("缺少必要参数");
        }

        // 可选：检查当前用户是否有权限退出（如自己或管理员）
        if (!currentUserId.equals(userId)) {
            String groupOwnerId = userListService.getGroupOwnerId(groupId);
            if (groupOwnerId == null || !groupOwnerId.equals(currentUserId)) {
                return ResultUtil.Fail("没有权限操作");
            }
        }

        boolean success = userListService.removeUserFromGroup(userId, groupId);
        if (success) {
            return ResultUtil.Succeed("退出成功");
        } else {
            return ResultUtil.Fail("退出失败");
        }
    }

    /**
     * 解散群聊（仅限群主）
     */
    @PostMapping("/disband")
    public Object disbandGroup(@Userid String currentUserId,
                               @RequestBody Map<String, String> payload) {
        String groupId = payload.get("groupId");
        String ownerId = payload.get("ownerId");

        // 参数校验
        if (groupId == null || ownerId == null) {
            return ResultUtil.Fail("缺少必要参数");
        }

        // 默认群不能解散
        if ("group_1".equals(groupId)) {
            return ResultUtil.Fail("默认群不允许解散");
        }

        // 检查是否是群主
        String groupOwnerId = userListService.getGroupOwnerId(groupId);
        if (groupOwnerId == null || !groupOwnerId.equals(ownerId)) {
            return ResultUtil.Fail("您不是群主，无法解散该群");
        }

        // 执行解散逻辑
        boolean success = userListService.disbandGroup(groupId, ownerId);
        return ResultUtil.ResultByFlag(success, "解散成功", "解散失败");
    }


}
